"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '11/05/2025'
    comment: 智能翻译测试(API级黑盒)
"""
import requests
import time
import aiohttp
import asyncio

host = 'http://localhost:8000'
api_translate = f'{host}/api/v1/translate'
api_conversations = f'{host}/api/v1/translate/conversations'

# 需要翻译的文本列表
texts = list()

# 英文小故事
texts.append('Leo was a painter who saw the world in shades of grey. One autumn afternoon, he noticed a single, vibrant red leaf stuck to his dusty studio window. It clung there, trembling against the wind. For the first time in years, Leo felt a stir of inspiration. He mixed his paints, not with the usual gloom, but with a fiery hope, and began to paint the leaf, not as it was, but as a small, brave fire against the vast, grey sky.')

# 英文短句
texts.append('Machine learning is a subset of artificial intelligence that enables computers to learn without being explicitly programmed.')

# 随意字符
texts.append('afadwklfjaewkjgwpevnvewvewo')


async def post_translate(text):
    """
    :return:
    """
    async with aiohttp.ClientSession() as session:
        async with session.post(api_translate, json={'text': text}) as resp:
            if resp.status != 200:
                raise Exception(f'智能翻译请求失败')

            resp = await resp.json()

    data = resp.get('data')

    return data


async def post_conversations():
    """
    :return:
    """
    response = requests.get(api_conversations)
    if response.status_code != 200:
        raise Exception('智能翻译请求失败')

    result = response.json()

    return result.get('data')


async def main():
    """
    :return:
    """
    start_time = int(time.time())

    tasks = list()
    for idx, text in enumerate(texts):
        tasks.append(
            asyncio.create_task(post_translate(text=text), name=f'task{idx}')
        )
    await asyncio.gather(*tasks)

    # 结果输出
    for task in tasks:
        result = task.result()
        print(f'任务名: {task.get_name()} 结果: {result}')
        print(f'⭐️⭐️⭐️⭐️⭐️输出word文件链接: http://localhost:8000{result.get("word_document_url", '')}')

    # 取得AI对话记录
    data = await post_conversations()
    conversations = data.get('conversations', [])
    for conversation in conversations:
        print(f'用户说：{conversation.get("message")}')
        print(f'AI说：{conversation.get("reply")}')
        print(f'⭐️⭐️⭐️⭐️⭐️推理时长: {conversation.get("duration")}')

    end_time = int(time.time())
    print(f'⭐️⭐️⭐️⭐️⭐️总执行时长: {end_time - start_time} 秒')


if __name__ == "__main__":

    asyncio.run(main())
